window.addEvent('domready', function() {
	$$('.panel').setOpacity(0.5);
	$$('.panel *').setOpacity(1);
	$('nojs').setStyle('display', 'none');
//	$$('#menu *').addEvent('click', menuClick);
	$$('body').addEvent('click', overallClick);
//	play('http://radio.echo.msk.ru:8000/listen');
});

window.FxRunning = [];	
window.stopFx = [];
window.FxCounterIn = [];
window.FxCounterOut = [];

function menuClick(elem)
{	
	if (this.setStyle) elem = this; 
	if ($(elem).hasClass('active')) return;
	$$(['li.active', elem]).toggleClass("active");
}

//$$('#menu li').addEvent('click', menuClick);

//returns XML-record
function RQL(path, order) {
	
}

function RQLUpdate(xml) {

}

function toHTML(xml, xslt) {

}

function unHTML(html, xslt) {

}



function overallClick(evt)
{
	var target = evt.target;
	if ($(target).getProperty('ajax')) {
		document.location = '#'+$(target).getProperty('ajax');
		return;
	}
	var parent = target.parentNode;
	while(parent.getProperty) {
		if ($(parent).getProperty('ajax')) {
			document.location = '#'+$(parent).getProperty('ajax');
			return;
		}
		parent = parent.parentNode;
	}
} 

document.location.onchange = function (newloc) {
	var anchor = '';
	anchor  = getAnchor(newloc);
	runLogo();
	pageUpdate(anchor);
	stopLogo();
}

function pageUpdate(anchor) {
	if (!anchor) anchor = 'timeline@data';
	var link = longAjaxLink(anchor);
	execLongLink(link);
	return;
	var links = $$('[ajax='+anchor+']');
	for (var x = 0; x < links.length; x++) {
		links[x].parentNode.getElements('.active').removeClass('active');
	}
	links.addClass('active');
}

function execLongLink(link) {
	var cur = link.shift();
	document.title += '  l:'+cur.model;
	if (link.length > 0) {
		document.title += '>';
		cur.onload = function() {
			execLongLink(link);
		}
	}
	cur.application = 'gui';
	loadState(cur);
}

function runLogo() {
	if(window.FxRunning['logo'] == true) return;
	logoFx('logo', 'opacity', 1, 0.5, 50, true);
}

function logoFx(elemId, prop, start, stop, int, debug) {
	if (window.stopFx[elemId] == true) {
		window.stopFx[elemId] = false;
		window.FxRunning[elemId] = false;
		return;
	}
	
	window.logoFxRunning = true;
	var logos = $$('#'+elemId+' *');
	var MyFx = new Fx( $$('#'+elemId+' *'));
	MyFx.start({opacity: 0.5});
	logos.setStyle(prop, start);
	document.getElementById(elemId).activeNodeIn = 0;
	document.getElementById(elemId).activeNodeOut = 0;
	window.FxCounterOut[elemId] = 0;
	for (var x=1; x<($(elemId).childNodes.length+1); x++) 
	{	
		setTimeout("fxDo('"+elemId+"', 'In', '"+prop+"', '"+stop+"');", x*100);
		setTimeout("fxDo('"+elemId+"', 'Out', '"+prop+"', '"+start+"');", x*(100+int));
	}
	window.FxRunning[elemId] = false;
	setTimeout("logoFx('"+elemId+"', '"+prop+"', '"+start+"', '"+stop+"', '"+int+"', "+debug+")",x*(100+int));
}

function fxDo(elem,  op, prop, val) {
//	$('data').innerHTML += op+' (#'+elem+' > '+document.getElementById(elem)['activeNode'+op]+'): ';
	var target = $(elem).childNodes[$(elem)['activeNode'+op]];
	document.getElementById(elem)['activeNode'+op] += 1;
//	$('data').innerHTML += target.id+'.'+prop+' = '+val+'<br/>';
	target.setStyle(prop, val);
}

function stopLogo() {
	window.stopFx['logo'] = true;
}

function stopFx(id) {
	window.stopFx[id] = true;
	$('data').innerHTML += id+': fx stoped<br/>';
}

function checkLocation() {
	if(window.locationOld != document.location) {
		window.locationOld = ''+document.location;
		if(document.location.onchange) document.location.onchange(document.location);
	}
}
window.locationCheckInterval = setInterval(checkLocation, 50);

function getAnchor(url) {
	if(!url) return '';
	var res = '';
	var url = new String(url);
	res = url.split('#', 2);
	
	return ''+res[1];
}

function loginInputHandler(event, elem) {
	if (event.keyCode == 27) {
		$('login').value = '';
		var myFx = new Fx('auth-form', {duration: 100});
		myFx.start({top: [-25, 0]});
		$('login').focus();
		return;
	}		
	if((event.keyCode != 13) && (event.keyCode != 9)) return;
	if (elem.id == 'login') {
		try {
			event.stopPropagation();
		} catch(x) {
			event.preventDefault();
		}
		$('pass').value = '';
		var myFx = new Fx.Morph('auth-form', {duration: 100});
		myFx.start({top: [0, -25]});
		setTimeout("$('pass').focus();", 100);
	} else {
		var myFx = new Fx.Morph('auth-form', {duration: 100});
		myFx.start({top: [-25, -50]});
		$('wait').setStyles({
			'text-align': 'center'
		});
		logoFx('wait', 'font-size', '12', '20', 100, false);
		setTimeout("stopFx('wait')", 300);				
	}
	return false;
}

 function getMimeType()  {
    var mimeType = "application/x-mplayer2"; //default
    var agt=navigator.userAgent.toLowerCase();
    if (navigator.mimeTypes && agt.indexOf("windows")==-1) {
       //non-IE, no-Windows
       var plugin=navigator.mimeTypes["audio/mpeg"].enabledPlugin;
       if (plugin) mimeType="audio/mpeg" //Mac/Safari & Linux/FFox
    }//end no-Windows
    return mimeType;
 }

 function play(wav_file)
 {
    var player = $('player'); 
    if (player == null) {
    	player = new Element('div');
    	player.id = 'player';
    	player.injectInside($$('body'));
    }
    player.innerHTML = "<object id='playera' src='"+wav_file+"' width='100' height='100' autostart='1' loop='0' height='0px' width='0px' type='"+getMimeType()+"'>\r\n"+
    "\t<param name='VOLUME' value='10'/>\n"+
    "</object>";
    window.player = $('playera');
 }
 
 function stopPlay() {
 	if ($('player')) {
 		$('player').innerHTML = '';
 	}
 }
 
function var_dump(element, depth, tab)
{
    if(!depth)
        depth = 0;
    if(!tab)
        tab = '';
       
    tab += '\t';
    string = '';
   
    //Loop through all the child objects in element
    for(property in element)
    {
        try {
	        //Add the name and value of the child object
	        string += tab + property          
	        //Check if the child is an object
	        if(typeof element[property] == 'object')
	            string += ': target is object.\n';   
	        else
	            string += ': '+ element[property] + ''+ '\n';
	    } catch (x) {
	    	string += '\n'+property+': exception!';
	    }
    }
   
       
    return string; 
}

function loadPage(pageName) {
	
}

function loadState(options, myModel) {
	var url = 'index.php?query_id=0&query_type=XML';
	for (var x in options) {
		if (!options[x]) continue;
		if (x == 'view_xslt') {
			var view = expandXSLTName(options[x]);
			continue;
		} 
		if (x == 'edit_xslt') {
			var edit = expandXSLTName(options[x]);
			continue;
		}
		if (x == 'target') {
			var target = options[x];
			continue;
		}
		if (x == 'onload') {
			var onload = options[x];
			continue;
		}		
		url+= '&'+x+'='+options[x];
	}
	
	// models caching
	if (!window.__models) window.__models = [];
	if (!window.__models[url]) {
		window.__models[url] = getModel(url);
	} else { 
		window.__models[url].reload();
	}
	var myModel = window.__models[url]; 
	
	var modelText = getModelText(myModel);
	
	
	if (x = modelText.match(/xml-stylesheet type='text.xsl' href='[^>]*'/)) {
		x = String(x);
		x = x.split(/href='/);
		x = String(x[1]);
		x = x.substr(0, x.length-1);
		x = x.replace(/&amp;/g, '&');
		view = x;
	} 
	if (!view) view = expandXSLTName('noview');
	
	var showView = loadView(view);
	if (edit) {
		var editView = getView(edit);
		showView.behaviors['editModel'] = {
			onclick: function (evt) {
				editView.render(myModel, target);
				return false;
			}
		};
		editView.behaviors['saveModel'] = {
			onclick: function (evt) {
				myModel.updateFrom(editView);
				showView.render(myModel, target);
				return false;
			}
		};
	}
	showView.render(myModel, target);
	if (onload) onload.call();
	return false;
}

/** 
 * 
 * @param model
 * @return String
 */
function getModelText(model) {
	if (!model.ready) return '';
	if (model.document.xml) {
		return model.document.xml
	} else { 
		var ser = new XMLSerializer();
		return ser.serializeToString(model.document);
	}
}

function expandXSLTName(name) {
	return 'index.php?query_id=0&query_type=XSLT&file='+name;
}

function longAjaxLink(url) {
	url = String(url);
	var tmp = url.split(/\./g);
	var res = {};
	var temp;
	var nodesArray = [];
	var nodesByTarget = [];
	for(var x = 0; x < tmp.length; x++) {
		temp = parseAjaxLink(tmp[x]);
		nodesArray[x] = temp;
		if (!nodesByTarget[temp.target]) nodesByTarget[temp.target] = [];
		nodesByTarget[temp.target].push(x);
	}
	var result = [];
	for(var x=tmp.length-1; x>-1; x--) {
		var t = nodesArray[x].target;
		if (nodesByTarget[t].length > 1) {
			x = nodesByTarget[t][0];
			var act = nodesByTarget[t].pop();
		} else {
			var act = x;
		}
		result.unshift(nodesArray[act]);
	}
	return result;
}

function parseAjaxLink(link) {	
	var regexp;
	regexp = /([^@]+)@([^:]+)(:([^:]+)(:([^:]+))?)?/;
	var tmp = [];
	tmp = regexp.exec(link);
	var res = {
		model: tmp[1],
		target: tmp[2],
		view_xslt: tmp[4],
		edit_xslt: tmp[6]
	};
	
	return res;
}

function loadView(vname, beh) {
	if (!window.__views) window.__views = [];
	if (window.__views[vname]) 
	{
		var ret = window.__views[vname];
	} else {
		var ret = getView(vname);
	}
	ret.behaviors = beh;
	return ret;
}
